import logging
import os
from pathlib import Path
from typing import Any, Dict, List, Optional

from openai import OpenAI


class OpenAIProvider:
    """Provider for OpenAI text-to-speech synthesis."""

    def __init__(self, api_key: Optional[str] = None, api_base: Optional[str] = None):
        """Initialize the OpenAI TTS provider.

        Args:
            api_key: The OpenAI API key. If not provided, will try to get from environment.
        """
        self.api_key = api_key or os.environ.get("OPENAI_API_KEY")
        if not self.api_key:
            raise ValueError(
                "OpenAI API key not provided and not found in environment variables"
            )
        self.api_base = api_base or os.environ.get("OPENAI_API_BASE")

        self.client = OpenAI(api_key=self.api_key, base_url=self.api_base)

    def synthesize_text(
        self,
        text: str,
        output_file: str,
        voice: str = "alloy",
        model: str = "tts-1",
        instructions: Optional[str] = None,
    ) -> str:
        """Synthesize a single text utterance to audio file.

        Args:
            text: The text to synthesize
            output_file: Path to save the audio file
            voice: Voice to use (alloy, echo, fable, onyx, nova, shimmer)
            model: TTS model to use (tts-1, tts-1-hd)
            instructions: Optional voice instructions

        Returns:
            Path to the generated audio file
        """
        output_path = Path(output_file)

        with self.client.audio.speech.with_streaming_response.create(
            model=model,
            voice=voice,
            input=text,
            instructions=instructions,
        ) as response:
            response.stream_to_file(output_path)

        return str(output_path)

    def synthesize_from_file(
        self,
        input_file: str,
        output_dir: str,
        voice: str = "alloy",
        model: str = "tts-1",
        instructions: Optional[str] = None,
        audio_format: str = "mp3",
    ) -> List[str]:
        """Synthesize audio for each line in a text file.

        Args:
            input_file: Path to the input text file (one utterance per line)
            output_dir: Directory to save the generated audio files
            voice: Voice to use (alloy, echo, fable, onyx, nova, shimmer)
            model: TTS model to use (tts-1, tts-1-hd)
            instructions: Optional voice instructions
            audio_format: Audio format (mp3)

        Returns:
            List of paths to the generated audio files
        """
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        output_files = []

        with open(input_file, "r", encoding="utf-8") as f:
            lines = [line.strip() for line in f.readlines() if line.strip()]

        for i, line in enumerate(lines):
            output_file = os.path.join(output_dir, f"audio_{i + 1}.{audio_format}")
            self.synthesize_text(line, output_file, voice, model, instructions)
            output_files.append(output_file)

        return output_files